package com.example.hxds.cst.service.impl;

import cn.hutool.core.map.MapUtil;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.example.hxds.common.exception.HxdsException;
import com.example.hxds.common.util.MicroAppUtil;
import com.example.hxds.cst.db.dao.CustomerDao;
import com.example.hxds.cst.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: CustomerServiceImpl
 * @Description: 乘客类实现
 * @Author: 丛雨
 * @Date: 2024/1/23 16:47
 */
@Service
@Slf4j
public class CustomerServiceImpl implements CustomerService {
    @Resource
    private CustomerDao customerDao;

    @Resource
    private MicroAppUtil microAppUtil;

    /**
     * 注册新用户
     *
     * @param param 注册需要的参数
     * @return 成功注册返回用户Id
     */
    @Override
    @Transactional
    @LcnTransaction
    public String registerNewCustomer(Map param) {
        String code = MapUtil.getStr(param, "code");
        String openId = microAppUtil.getOpenId(code);
        HashMap tempMap = new HashMap() {{
            put("openId", openId);
        }};

        if (customerDao.hasCustomer(tempMap) != 0) {
            throw new HxdsException("该微信无法注册");
        }

        param.put("openId", openId);
        customerDao.registerNewCustomer(param);

        String customerId = customerDao.searchCustomerId(openId);
        return customerId;
    }

    /**
     * 用户登录
     *
     * @param code 小程序临时授权码
     * @return 成功登录返回用户Id1
     */
    @Override
    public String login(String code) {
        String openId = microAppUtil.getOpenId(code);
        String customerId = customerDao.login(openId);
        customerId = (customerId != null) ? customerId : "";
        return customerId;
    }
}
